<template>
  <div>
    <div class="mod-user" v-if="visible">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item label="用户名：">
          <el-input size="small" v-model="dataForm.userName" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input size="small" v-model="dataForm.mobile" placeholder="手机号"   clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="getDataList()">查询</el-button>
          <el-button size="small" v-if="isAuth('sys:user:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <el-button size="small" v-if="isAuth('sys:user:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
          <el-button size="small"  type="success" @click="exportData()" :disabled="dataListSelections.length <= 0">批量导出Excel</el-button>
          <el-upload
              style="display: inline-block;margin-left: 10px"
              action="http://localhost:8080/sys/user/import"
              :headers="{token:this.$cookie.get('token')}"
              :show-file-list="false"
              :on-success="handleImport">
              <el-button size="small" plain type="primary">批量导入Excel</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <!-- 序号 -->
        <el-table-column
          type="index"
          header-align="center"
          align="center"
          width="50"
          label="序号" fixed="left">
        </el-table-column>
        <el-table-column
          prop="avatar"
          header-align="center"
          align="center"
          label="头像"
          width="80">
          <template slot-scope="scope">
            <img :src=scope.row.avatar  style="width: 50px;height: 50px;">
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          header-align="center"
          align="center"
          label="用户名"
          width="100">
        </el-table-column>

        <el-table-column
          prop="realName"
          header-align="center"
          align="center"
          label="真实姓名"
          width="100">
          <template slot-scope="scope">
           <el-tag  type="warning" effect="plain">{{ scope.row.realName }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="roleIdList"
          header-align="center"
          align="center"
          :show-overflow-tooltip="true"
          label="角色">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center;">
              <el-tag  type="warning" v-for="role in roleList" :key="role.roleId" v-if="scope.row.roleIdList.includes(role.roleId)"
                       size="small" style="margin-right: 5px;">
                {{ role.roleName }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          header-align="center"
          align="center"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          header-align="center"
          align="center"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="organizationsId"
          header-align="center"
          align="center"
          label="组织机构"
          width="100">
          <template slot-scope="scope">
            <el-tag >{{ getDepatName(scope.row.organizationsId) }}</el-tag>
          </template>
        </el-table-column>


        <el-table-column
          prop="files"
          header-align="center"
          align="center"
          width="160"
          label="合同文件">
          <template slot-scope="scope">
            <div v-if="scope.row.files">
              <i
                v-for="(fileUrl, index) in scope.row.files"
                :key="index"
                class="el-icon-document"
                style="cursor: pointer; margin-right: 10px;color: red"
                @click="openPdf(fileUrl)"
              ></i>
            </div>
            <span v-else>无合同文件</span>
          </template>
        </el-table-column>


        <el-table-column
          prop="status"
          header-align="center"
          align="center"
          label="状态"
          width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" size="small" type="danger">禁用</el-tag>
            <el-tag v-else size="small" type="success">正常</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          header-align="center"
          align="center"
          width="160"
          label="创建时间">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button  v-if="isAuth('sys:user:info')" type="text" size="small" @click="userDetails(scope.row)" style="color: gold;">详情</el-button>
            <el-button v-if="isAuth('sys:user:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.userId)">修改</el-button>
            <el-button v-if="isAuth('sys:user:delete')" type="text" size="small" @click="deleteHandle(scope.row.userId)" style="color: red;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
    <!-- 详情页面 -->
    <user-details ref="userDetails" @goBack="goback()" v-if="detailVisible"></user-details>
  </div>

</template>

<script>
import AddOrUpdate from './user-add-or-update';
import userDetails from './user-userDetails';

export default {
  data () {
    return {
      dataForm: {
        userName: '',
        mobile:''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      departList: [],  // 部门列表
      roleList: [],  // 角色列表
      visible: true, //
      detailVisible: false // 详情页面
    }
  },
  components: {
    AddOrUpdate,
    userDetails
  },
  activated () {
    this.getDataList(); // 获取数据列表
    this.getDepartList();  // 获取部门列表
    this.getRoleList();  // 获取角色列表
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/sys/user/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'username': this.dataForm.userName,
          'mobile':this.dataForm.mobile
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list.map(item => {
            if (typeof item.files ==='string') {
              item.files = item.files.split(',');
            }
            return item;
          });
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 打开 PDF 文件
    openPdf(ossFileUrl) {
        window.open(ossFileUrl);
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    //详情页面
    userDetails(row) {
      this.detailVisible = true    // 打开详情弹窗
      this.visible = false   //父组件的显示状态（详情界面才需要设置）
      this.$nextTick(() => {
        this.$refs.userDetails.init(row)  //访问子组件的方法
      })
    },
    // 详情界面返回
    goback() {
      this.detailVisible = false;
      this.visible = true;
    },
    // 删除
    deleteHandle (id) {
      var userIds = id ? [id] : this.dataListSelections.map(item => {
        return item.userId;
      });
      this.$confirm(`确定对[id=${userIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/user/delete'),
          method: 'post',
          data: this.$http.adornData(userIds, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      }).catch(() => {});
    },
    // 获取部门列表
    getDepartList() {
      this.$http({
        url: this.$http.adornUrl('/sys/organizations/list'),
        method: 'get',
        data: this.$http.adornData({})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.departList = data.page.list.map(item => ({
            value: item.id,
            label: item.name
          }));
          console.log("部门列表", this.departList);
        } else {
          console.error("获取部门列表失败", data.msg);
        }
      }).catch(error => {
        console.error("获取部门列表失败", error);
      });
    },
    // 获取角色列表
    getRoleList() {
      this.$http({
        url: this.$http.adornUrl("/sys/role/select"),
        method: "get",
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.roleList = data.list;
          console.log("角色列表", this.roleList);
        } else {
          console.error("获取角色列表失败", data.msg);
        }
      }).catch(error => {
        console.error("获取角色列表失败", error);
      });
    },

    // 导出Excel
    exportData(id) {
      var userIds = id ? [id] : this.dataListSelections.map(item => {
        return item.userId;
      });
      this.$confirm('确认导出数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 只传递需要的 ID 数组，确保数据格式符合后端预期
        // const idsToExport = this.dataListSelections.map(item => item.id); // 假设每个选项都有一个 id 属性

        this.$http({
          url: this.$http.adornUrl('/sys/user/export'),
          method: 'post',
          responseType: 'blob',  // 确保后端返回的是文件流
          data: this.$http.adornData(userIds, false)
        }).then(response => {
          // 确认响应返回的内容是文件
          if (response && response.data) {
            const contentDisposition = response.headers['content-disposition'];
            const fileName = contentDisposition.split('filename=')[1].trim().replace(/"/g, '');

            // 创建一个 URL 对象并触发下载
            const blob = new Blob([response.data]);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = fileName;
            link.click();

            // 提示导出成功
            this.$message({
              message: '导出成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            // 如果返回数据不符合预期，给用户提示错误
            this.$message.error('导出失败');
          }
        }).catch(() => {
          this.$message.error('请求失败');
        });
      }).catch(() => {});
    },

   //批量导入
   handleImport(res,file,fileList){
      console.log('res：'+res)
      if (res.code === 0){
        this.$message.success("Excel文件上传成功")
        this.getDataList()
      }else {
        this.$message.error(res.data)
      }
    },



    // 计算部门名称
    getDepatName(organizationsId) {
      const depart = this.departList.find(item => item.value === organizationsId);
      return depart ? depart.label : '未分配';
    }
  }
}
</script>
